package com.example.park_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.park_management.common.PageParam;
import com.example.park_management.common.Result;
import com.example.park_management.domain.Notices;
import com.example.park_management.domain.ParkingSpaces;
import com.example.park_management.service.NoticesService;
import com.mysql.cj.protocol.x.Notice;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/notices")
public class NoticesController {

    @Resource
    NoticesService noticesService;

    @PostMapping("/")
    public Result add(@RequestBody Notices notices){
        try{
            if (notices.getDatePublished().equals(null)){
                return Result.fail("必填属性为空");
            }
            boolean save = noticesService.save(notices);
            return save?Result.success():Result.fail();
        }catch (Exception e){
            return Result.fail("输入格式异常！");
        }
    }

    @PutMapping("/")
    public Result update(@RequestBody Notices notices){
        try{
            if (notices.getDatePublished().equals(null)){
                return Result.fail("必填属性为空");
            }
            boolean save = noticesService.updateById(notices);
            return save?Result.success():Result.fail();
        }catch (NumberFormatException e) {
            return Result.fail("输入格式异常！");
        }
    }

    @DeleteMapping("/{noticeId}")
    public Result delete(@PathVariable Integer noticeId){
        boolean b = noticesService.removeById(noticeId);
        return b?Result.success():Result.fail();
    }

    @PostMapping("/page")
    public Result page(@RequestBody PageParam<Notices> pageParam){
        Page<Notices> noticesPage = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
//        noticesService.page(noticesPage);

        QueryWrapper<Notices> noticesQueryWrapper = new QueryWrapper<>();
        if (pageParam.getData() != null){
            if (pageParam.getData().getAuthor() != null){
                noticesQueryWrapper.like("author", pageParam.getData().getAuthor());
            }

            if (pageParam.getData().getTitle() != null){
                noticesQueryWrapper.like("title", pageParam.getData().getTitle());
            }
            if (pageParam.getData().getContent() != null){
                noticesQueryWrapper.like("content", pageParam.getData().getContent());
            }
        }
        noticesService.page(noticesPage,noticesQueryWrapper);
        return Result.success(noticesPage.getRecords(),noticesPage.getTotal());
    }

}
